﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Messenger_Client
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const int BUFSIZE = 1116;

        public MainWindow()
        {
            InitializeComponent();
            startServer();
            Thread myThread = new Thread(new ThreadStart(delegate() { listenMessageFromServer(); }));
            myThread.Start();
        }

        public void startServer()
        {
            //Create the TCP client and connect
            TcpClient client = new TcpClient();
            byte[] byteBuffer = Encoding.ASCII.GetBytes("Ceci est un test");

            client.Connect(IPAddress.Parse("127.0.0.1"), 1900);
            NetworkStream netStream = client.GetStream();

            netStream.Write(byteBuffer, 0, byteBuffer.Length);

            int totalBytesRcvd = 0;
            int bytesRcvd = 0;

            while (totalBytesRcvd < byteBuffer.Length)
            {
                if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
                byteBuffer.Length - totalBytesRcvd)) == 0)
                {
                    listBox1.Items.Add("Connection closed prematurely.");
                    break;
                }
                totalBytesRcvd += bytesRcvd;
            }
            listBox1.Items.Add(String.Format("Received {0} bytes from server: {1}", totalBytesRcvd,Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd)));

            client.Close();
        }

        private void sendMessageToserver(object sender, EventArgs e, string message) {
            TcpClient client = new TcpClient();
            byte[] byteBuffer = Encoding.ASCII.GetBytes(message);

            client.Connect(IPAddress.Parse("127.0.0.1"), 1900);
            NetworkStream netStream = client.GetStream();

            netStream.Write(byteBuffer, 0, byteBuffer.Length);

            int totalBytesRcvd = 0;
            int bytesRcvd = 0;

            while (totalBytesRcvd < byteBuffer.Length)
            {
                if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
                byteBuffer.Length - totalBytesRcvd)) == 0)
                {
                    listBox1.Items.Add("Connection closed prematurely.");
                    break;
                }
                totalBytesRcvd += bytesRcvd;
            }
            listBox1.Items.Add(String.Format("Received {0} bytes from server: {1}", totalBytesRcvd, Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd)));

            client.Close();
        }

        private void listenMessageFromServer() {
            TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1910));
            listener.Start();

            byte[] rcvBuffer = new byte[BUFSIZE];
            int bytesRcvd;
            for (; ; )
            {
                TcpClient client = null;
                NetworkStream netStream = null;
                rcvBuffer = new byte[BUFSIZE];
                try
                {
                    client = listener.AcceptTcpClient();
                    netStream = client.GetStream();

                    int totalBytesEchoed = 0;
                    while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
                    {
                        netStream.Write(rcvBuffer, 0, bytesRcvd);
                        totalBytesEchoed += bytesRcvd;
                        string encodedValue = Encoding.ASCII.GetString(rcvBuffer).Replace("\0", "");
                        listBox1.Dispatcher.BeginInvoke(new Action(delegate(){
                            listBox1.Items.Add("Message : " + encodedValue);
                        }));
                    }
                    
                    
                    netStream.Close();
                    client.Close();

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    netStream.Close();
                }
            }
        }

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            sendMessageToserver(sender, e, TextBox1.Text);
            TextBox1.Text = "";
        }   
    }
}
